import json

from django import forms
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from manage_worker import models
from manage_worker.utills.bootsrtap import BootStrapModelForm
from manage_worker.utills.pagination import Pagination


class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = '__all__'
        widgets = {
            'detail': forms.TextInput
        }


def task_list(request):
    queryset = models.Task.objects.all().order_by('-id')
    form = TaskModelForm()
    page_object = Pagination(request, queryset=queryset)
    context = {
        'form': form,
        'queryset': page_object.page_queryset,  # 分完页的数据
        'page_string': page_object.html()  # 页码
    }

    return render(request, 'task_list.html', context)


# 免除验证csrf_token的装饰器
@csrf_exempt
def task_ajax(request):
    print(request.POST)
    data_list = {'status': True, 'data': [11, 22, 34, 55]}
    # json_str = json.dumps(data_list)
    # return HttpResponse(json_str)
    # django自带的序列化方法
    return JsonResponse(data_list)


@csrf_exempt
def task_add(request):
    print(request.POST)
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_list = {'status': True, 'data': [11, 22, 34, 55]}
        return JsonResponse(data_list)
    data_list = {'status': False, 'error': form.errors}
    return JsonResponse(data_list)
